package com.cdn.clock.config;

import com.cdn.clock.component.LockComponent;
import com.cdn.clock.component.lock.RedisLockComponent;
import com.cdn.clock.component.lock.RedissionLockComponent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 **/
public class LockConfig {


    private static final Log log = LogFactory.getLog(LockConfig.class);

    @Bean("redisLockTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        return redisTemplate;
    }

    /**
     * @author 蔡定努
     */
    @Bean
    @ConditionalOnProperty(prefix = "clock", name = "type", havingValue = "redis")
    public LockComponent redisLockComponent() {
        log.info("init RedisLockComponent success");
        return new RedisLockComponent();
    }


    @Autowired
    RedissonClient redissonClient;

    @Bean
    @ConditionalOnProperty(prefix = "clock", name = "type", havingValue = "redission", matchIfMissing = true)
    @ConditionalOnMissingBean(name = "redisLockComponent")
    public LockComponent redissionLockComponent() {
        RedissionLockComponent redissionLockComponent = new RedissionLockComponent();
        redissionLockComponent.setRedissonClient(redissonClient);
        log.info("init RedissionLockComponent success");
        return redissionLockComponent;
    }


    /**
     * @author 蔡定努
     */
    @ConditionalOnProperty(prefix = "clock", name = "type", havingValue = "redis")
    @Bean(initMethod = "init",destroyMethod = "shutdown")
    public ClogThreadPoolTask clogThreadPoolTask() {
        return new ClogThreadPoolTask();
    }



}
